import React, {
  useState,
  CSSProperties,
  useImperativeHandle,
  forwardRef,
  useEffect,
  useRef,
  useMemo,
} from 'react';
import { Layout, Button } from 'antd';
import { RightOutlined } from '@ant-design/icons';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { SvgIcon } from '@/components/icon';
import Back from '@/pages/app-orchestration/components/Back';
import { useRouter } from '@/router/hooks';
import { useConfigActions, useKnowStatus, useWorkBench } from '@/store/configStore';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { useDatasetStore } from '@/store/datasetStore';
import { SetPoliciesReq } from '@/common/types/org';
import PublishComponent from './PublishComponent';
import { AppType, UserRoleEnum } from '@/common/app/constants';
import { useConfig } from '@/store/configStore';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import { useTranslation } from 'react-i18next';
import { StorageEnum } from '@/types/enum';
import { getItem } from '@/utils/storage';
import { MenuProps } from 'antd';

const { Header: AntHeader } = Layout;

// 定义内容类型
type ContentType =
  | 'chat'
  | 'history'
  | 'datasets'
  | 'api-manage'
  | 'extension-manage'
  | 'permission-manage'
  | 'knowledge-manage'
  | 'report'
  | 'app-test'
  | 'share'
  | null;
// 定义权限管理子页面类型
type PermissionSubPageType = 'permission' | 'user' | 'role' | 'share' | 'qaPermission';
// 定义知识管理子页面类型
type KnowledgeSubPageType = 'datasets' | 'know-gov' | 'api' | 'extension';

// 修改navItems定义，将path改为contentType
const navItems = [
  {
    key: 'orchestration',
    label: '编排',
    contentType: 'chat' as ContentType,
    icon: 'ai-orch-arrange',
  },
  {
    key: 'knowledge',
    label: '知识管理',
    contentType: 'knowledge-manage' as ContentType,
    icon: 'ai-orch-dataset',
  },
  {
    key: 'permission',
    label: '权限管理',
    contentType: 'permission-manage' as ContentType,
    icon: 'ai-orch-permission',
  },
  {
    key: 'share',
    label: '对外分享',
    contentType: 'share' as ContentType,
    icon: 'ai-orch-permission',
  },
  {
    key: 'data',
    label: '应用看板',
    contentType: 'report' as ContentType,
    icon: 'ai-orch-data',
  },
  {
    key: 'test',
    label: '应用测试',
    contentType: 'app-test' as ContentType,
    icon: 'ai-orch-data',
  },
];

// 添加一个函数来获取过滤后的导航项
const getFilteredNavItems = (
  isPreview: boolean,
  userRole: string | null,
  appDetail: any,
  isDisableDataset: boolean,
  isTianGongManager: boolean,
) => {
  let filteredItems = [...navItems];

  if (isDisableDataset) {
    filteredItems = filteredItems.filter((item) => item.key != 'knowledge');
  }

  if (appDetail?.appType == AppType.fusion) {
    filteredItems = filteredItems.filter((item) =>
      ['orchestration', 'permission', 'data'].includes(item.key),
    );
  }

  // 如果不是管理员，只显示编排和知识管理
  if (userRole != UserRoleEnum?.admin && !isPreview) {
    filteredItems = filteredItems.filter(
      // (item) => item.key === 'orchestration' || item.key === 'knowledge',
      (item) => item.key === 'knowledge',
    );
    // 修改编排标签为问答
    filteredItems = filteredItems.map((item) =>
      item.key === 'orchestration' ? { ...item, label: '问答' } : item,
    );
  }

  // 知识审核员，只显示问答
  if (userRole == UserRoleEnum?.knowledge_reviewer && !isPreview) {
    filteredItems = filteredItems.filter((item) => item.key === 'orchestration');
    // 修改编排标签为问答
    filteredItems = filteredItems.map((item) =>
      item.key === 'orchestration' ? { ...item, label: '问答' } : item,
    );
  }

  // 如果是预览模式，仅展示问答
  if (isPreview) {
    filteredItems = filteredItems
      .filter((item) => item.key == 'orchestration')
      .map((item) => (item.key === 'orchestration' ? { ...item, label: '预览' } : item));
  }

  // 根据 TiangongManagerRoles 过滤菜单项
  if (isTianGongManager) {
    filteredItems = filteredItems.filter(
      (item) => item.key !== 'permission' && item.key !== 'test',
    );
  }

  return filteredItems;
};

interface HeaderProps {
  isHistoryMode: boolean;
  onToggleHistoryMode: () => void;
  onRestoreVersion: (versionId: string) => void;
  onSave: (
    is_publish?: boolean,
    permissionConfig?: SetPoliciesReq['statements'],
    is_all_can_qa?: boolean,
    is_auto_save?: boolean,
  ) => Promise<void>;
  onNavChange: (
    key: string,
    contentType: ContentType,
    permissionSubPage?: PermissionSubPageType,
    knowledgeSubPage?: KnowledgeSubPageType,
  ) => void;
  selectedHistoryVersion: string | null;
  configurationsTemp: any[];
  isPreview: boolean;
  onApprove?: () => void;
  onReject?: () => void;
  onReturn?: () => void;
  previewBtn?: boolean;
  onCheckTabStatus?: () => boolean;
  activeType: string;
}

export interface HeaderRef {
  switchToKnowledgeTab: () => void;
}

const Header = forwardRef<HeaderRef, HeaderProps>(
  (
    {
      isHistoryMode,
      onToggleHistoryMode,
      onRestoreVersion,
      onSave,
      onNavChange,
      selectedHistoryVersion,
      configurationsTemp,
      isPreview,
      onApprove,
      onReject,
      onReturn,
      previewBtn,
      activeType,
      onCheckTabStatus,
    },
    ref,
  ) => {
    const knowStatus = useKnowStatus();
    const { setIsKnow } = useConfigActions();

    const navigate = useNavigate();
    const [activeKey, setActiveKey] = useState('orchestration');
    // 跟踪当前选中的权限管理子页面
    const [activePermissionSubPage, setActivePermissionSubPage] =
      useState<PermissionSubPageType>('qaPermission');
    // 跟踪当前选中的知识管理子页面
    const [activeKnowledgeSubPage, setActiveKnowledgeSubPage] =
      useState<KnowledgeSubPageType>('datasets');
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [saveStatus, setSaveStatus] = useState(false);
    // 添加自动保存时间状态
    const [lastAutoSaveTime, setLastAutoSaveTime] = useState<string | null>(null);
    const autoSaveTimerRef = useRef<NodeJS.Timeout | null>(null);

    const { getParentId } = useDatasetStore();
    const router = useRouter();
    const workbench = useWorkBench();

    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    const appId = queryParams.get('appId') || '';

    const {
      configurations,
      userRole,
      appName,
      permissionConfig,
      appDetail,
      appDetailInit,
      appLogo,
    } = useOrchestrationStore();

    const defaultValue = permissionConfig.map((item) => ({
      id: item.target?.target_id,
      name: item.target?.target_name,
      type: item.target?.target_type,
      resources: item.resources,
    }));

    const appNameConfig =
      (configurations.find((config) => config.name === 'app_name')?.default_value as string) ||
      appName;

    const appLogoConfig =
      (configurations.find((config) => config.name === 'app_logo')?.default_value as string) ||
      appLogo;

    const isDisableDataset =
      configurations?.find((config) => config.name === 'disable_dataset')?.default_value === '1' ||
      false;

    // 新增逻辑：从本地缓存读取天工角色状态
    const userInfo_tiangong = getItem<any>(StorageEnum.User);
    const isTianGongManager = Boolean(
      userInfo_tiangong?.is_TianGong === 'true' || userInfo_tiangong?.is_TianGong === true,
    );

    // 监听配置变化
    useEffect(() => {
      // 检查 configurationsTemp 中的值是否在 configurations 中发生变化
      let hasChanges = configurationsTemp.some((tempConfig) => {
        const currentConfig = configurations.find((config) => config.name === tempConfig.name);
        if (!currentConfig) return false;

        // 处理特殊值相等的情况
        const tempValue = tempConfig.default_value;
        const currentValue = currentConfig.default_value;

        // 检查 '0' 和 false, '1' 和 true, '' 和 'default' 的相等情况
        if (
          (tempValue === '0' && currentValue === false) ||
          (tempValue === false && currentValue === '0') ||
          (tempValue === '1' && currentValue === true) ||
          (tempValue === true && currentValue === '1') ||
          (tempValue === '' && currentValue === 'default') ||
          (tempValue === 'default' && currentValue === '')
        ) {
          return false;
        }

        const isDifferent = JSON.stringify(tempValue) !== JSON.stringify(currentValue);
        if (isDifferent) {
          console.log('配置值更新:', {
            name: tempConfig.name,
            newValue: currentValue,
            oldValue: tempValue,
          });
        }
        return isDifferent;
      });

      // model 为 JSON，需深度比较；fusionApp 为数组，需比较 id 和顺序，需兼容 null/undefined
      const isModelEqual =
        JSON.stringify(appDetailInit?.model ?? {}) === JSON.stringify(appDetail?.model ?? {});
      if (!isModelEqual) {
        // 打印 model 不一样的地方
        console.log('model 不一致:', {
          appDetailInitModel: appDetailInit?.model,
          appDetailModel: appDetail?.model,
        });
      }

      const getFusionAppIds = (arr: any[] = []) =>
        Array.isArray(arr) ? arr.map((item) => item?.appId) : [];
      const fusionAppInitIds = getFusionAppIds(appDetailInit?.fusionApp);
      const fusionAppIds = getFusionAppIds(appDetail?.fusionApp);

      let isFusionAppEqual: boolean;
      if (Array.isArray(appDetailInit?.fusionApp) && Array.isArray(appDetail?.fusionApp)) {
        isFusionAppEqual = JSON.stringify(fusionAppInitIds) === JSON.stringify(fusionAppIds);
        if (!isFusionAppEqual) {
          // 打印 fusionApp 不一样的地方
          console.log('fusionApp 不一致:', {
            appDetailInitFusionAppIds: fusionAppInitIds,
            appDetailFusionAppIds: fusionAppIds,
            appDetailInitFusionApp: appDetailInit?.fusionApp,
            appDetailFusionApp: appDetail?.fusionApp,
          });
        }
      } else {
        isFusionAppEqual = appDetailInit?.fusionApp === appDetail?.fusionApp;
        if (!isFusionAppEqual) {
          // 打印 fusionApp 不一样的地方
          console.log('fusionApp 不一致（非数组情况）:', {
            appDetailInitFusionApp: appDetailInit?.fusionApp,
            appDetailFusionApp: appDetail?.fusionApp,
          });
        }
      }

      const isInitInfoCompare = isModelEqual && isFusionAppEqual;

      setHasUnsavedChanges(hasChanges || !isInitInfoCompare);
    }, [configurationsTemp, configurations, appDetailInit]);

    // 添加自动保存功能
    useEffect(() => {
      // 只有在非预览模式且当前页面是编排页面且有未保存更改时才启用自动保存
      if (!isPreview && activeKey === 'orchestration' && hasUnsavedChanges) {
        // 清除之前的定时器
        if (autoSaveTimerRef.current) {
          clearTimeout(autoSaveTimerRef.current);
        }

        // 设置新的定时器，30秒后自动保存
        autoSaveTimerRef.current = setTimeout(async () => {
          try {
            await onSave(false, [], false, true);
            // 更新自动保存时间
            const now = new Date();
            const timeString = `${now.getHours().toString().padStart(2, '0')}:${now
              .getMinutes()
              .toString()
              .padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
            setLastAutoSaveTime(timeString);
          } catch (error) {
            console.error('自动保存失败:', error);
          }
        }, 30000); // 30秒
      }

      // 组件卸载时清除定时器
      return () => {
        if (autoSaveTimerRef.current) {
          clearTimeout(autoSaveTimerRef.current);
        }
      };
    }, [hasUnsavedChanges, isPreview, activeKey, onSave]);

    const handleNavClick = (item: { key: string; contentType: ContentType }) => {
      console.log('item============', item);

      //页面跳转的时候清空，parentId
      getParentId('');

      setActiveKey(item.key);

      // 根据点击的菜单项类型传递不同的子页面信息
      if (item.contentType === 'permission-manage') {
        onNavChange(item.key, item.contentType, activePermissionSubPage);
      } else if (item.contentType === 'knowledge-manage') {
        onNavChange(item.key, item.contentType, undefined, activeKnowledgeSubPage);
      } else {
        onNavChange(item.key, item.contentType);
      }
    };

    // 处理权限管理子菜单点击
    const handlePermissionSubMenuClick = ({ key }: { key: string }) => {
      const subPage = key as PermissionSubPageType;
      setActivePermissionSubPage(subPage);

      // 设置当前导航为权限管理
      const permissionItem = navItems.find((item) => item.key === 'permission');
      if (permissionItem) {
        setActiveKey(permissionItem.key);
        onNavChange(permissionItem.key, permissionItem.contentType, subPage);
      }
    };

    // 处理知识管理子菜单点击
    const handleKnowledgeSubMenuClick = ({ key }: { key: string }) => {
      const subPage = key as KnowledgeSubPageType;
      setActiveKnowledgeSubPage(subPage);

      // 设置当前导航为知识管理
      const knowledgeItem = navItems.find((item) => item.key === 'knowledge');
      if (knowledgeItem) {
        setActiveKey(knowledgeItem.key);
        onNavChange(knowledgeItem.key, knowledgeItem.contentType, undefined, subPage);
      }
    };

    // 跳转到知识管理标签
    const goToKnowledgeTab = (tab = 'knowledge') => {
      const knowledgeTab = navItems.find((item) => item.key === tab);
      if (knowledgeTab) {
        setActiveKey(knowledgeTab.key);
        onNavChange(knowledgeTab.key, knowledgeTab.contentType, undefined, activeKnowledgeSubPage);
      }
    };

    const buttonStyle: CSSProperties = {
      // borderRadius: '20px',
    };

    const getNavItemStyle = (key: string): CSSProperties => {
      if (key === activeKey) {
        return {
          // background: `linear-gradient(114.39deg, var(--brand-color-hover) 0%, var(--brand-color) 65.6%)`,
          // WebkitBackgroundClip: 'text',
          // WebkitTextFillColor: 'transparent',
          // backgroundClip: 'text',
          color: '#1B6DFA',
          cursor: 'pointer',
          height: '60px',
          display: 'flex',
          alignItems: 'center',
          position: 'relative',
        } as CSSProperties;
      }
      return {
        color: '#666C85',
        cursor: 'pointer',
        height: '60px',
        display: 'flex',
        alignItems: 'center',
        position: 'relative',
      } as CSSProperties;
    };

    // 暴露给父组件的方法
    useImperativeHandle(ref, () => ({
      switchToKnowledgeTab: () => {
        const knowledgeTab = navItems.find((item) => item.key === 'knowledge');
        if (knowledgeTab) {
          setActiveKey(knowledgeTab.key);
          onNavChange(
            knowledgeTab.key,
            knowledgeTab.contentType,
            undefined,
            activeKnowledgeSubPage,
          );
        }
      },
    }));

    const renderNavItem = (item: (typeof navItems)[0]) => {
      return (
        <div key={item.key} className="flex items-center">
          <div
            className={`text-base ${
              activeKey === item.key
                ? 'border-b-[3px] border-b-[@brand-color] font-[600] text-[#1B6DFA]'
                : 'border-b-[3px] border-b-[transparent] font-[400]'
            } `}
            style={getNavItemStyle(item.key)}
            onClick={() => handleNavClick(item)}
          >
            {/* <div className="flex items-center">
              <SvgIcon icon={item.icon} size={18} className="mr-1" />
            </div> */}
            {item.label}

            {/* {activeKey === item.key && (
              <div
                style={{
                  background: `linear-gradient(94.09deg, var(--brand-color-hover) 6.89%, var(--brand-color) 98%)`,
                  width: '14px',
                  height: '5px',
                  borderRadius: '20px',
                  position: 'absolute',
                  bottom: '10px',
                  left: '50%',
                  transform: 'translateX(-50%)',
                }}
              />
            )} */}
          </div>
        </div>
      );
    };

    const [filteredNavItems, setFilteredNavItems] = useState<typeof navItems>([]);

    // 监听 userRole 和 isPreview 的变化
    useEffect(() => {
      userRole &&
        setFilteredNavItems(getFilteredNavItems(isPreview, userRole, appDetail, isDisableDataset, isTianGongManager));
    }, [userRole, isPreview, appDetail, isDisableDataset, isTianGongManager]);

    useEffect(() => {
      if (activeKey != 'orchestration') {
        isHistoryMode && onToggleHistoryMode();
      }
    }, [activeKey]);

    useEffect(() => {
      return () => {
        setIsKnow(false);
      };
    }, []);

    useEffect(() => {
      if (activeType) {
        const targetNavItem = navItems.find((item) => item.contentType === activeType);
        if (targetNavItem) {
          handleNavClick(targetNavItem);
        }
      }
    }, [activeType]);

    return (
      <>
        <AntHeader
          style={{
            background: '#FFFFFF',
            lineHeight: 'normal',
            padding: '0 12px',
            // boxShadow: '0px 4px 20px 0px #0000000D',
          }}
          className="relative flex h-[60px] items-center justify-between border-b border-[#E5E6EB]"
        >
          <div className="flex items-center">
            <div className="flex">
              <Back
                // title={isPreview ? (previewBtn ? '审批历史' : '待审批应用') : '工作台'}
                title={''}
                confirmMessage={
                  hasUnsavedChanges && !isPreview ? '尚未保存，可能会丢失部分信息' : undefined
                }
                onOk={() => {
                  onSave(false);
                }}
                onBack={() => {
                  if (isPreview && onReturn) {
                    // 如果没有key参数，则跳转工作台
                    const params = new URLSearchParams(window.location.search);
                    if (!params.get('key')) {
                      router.push(workbench);
                      return;
                    }
                    onReturn();
                  } else {
                    router.push(workbench);
                  }
                }}
                isPreview={isPreview}
              />
              <div className="justify-left flex w-[300px] items-center">
                {appNameConfig && (
                  <>
                    {/* <RightOutlined
                      className="pl-2 pr-2 text-[#6C7180]"
                      style={{ fontSize: '9px' }}
                    /> */}
                    <AvatarDisplay
                      src={appLogoConfig}
                      size={32}
                      className="mx-2 h-[32px] w-[32px]"
                    />
                    <span
                      className="justify-left flex items-center overflow-hidden text-ellipsis whitespace-nowrap text-[16px] font-[600] text-[#1D2129]"
                      style={{ maxWidth: 300 }}
                      title={appNameConfig}
                    >
                      {appNameConfig}
                    </span>
                  </>
                )}
              </div>
            </div>
          </div>
          <div className="absolute left-1/2 top-0 flex translate-x-[-50%] items-center gap-8">
            {filteredNavItems.map(renderNavItem)}
          </div>

          {!isPreview ? (
            userRole != UserRoleEnum?.knowledge_reviewer ? (
              <div className="mr-2 flex max-w-[40%] items-center justify-end gap-2">
                {knowStatus && (
                  <div className=" text-@warning-color">
                    <SvgIcon icon="warning" size={16} className="mr-1" />
                    文件变更已保存，需发布审批后生效
                  </div>
                )}
                {isHistoryMode && activeKey === 'orchestration' ? (
                  <>
                    <Button
                      type="primary"
                      className="bg-[#7B67EE]"
                      style={buttonStyle}
                      onClick={() => onRestoreVersion(selectedHistoryVersion || '')}
                      disabled={!selectedHistoryVersion}
                    >
                      恢复
                    </Button>
                    <Button
                      className="border-[#D9D9D9] bg-[#ffffff] text-[#4E5969]"
                      style={buttonStyle}
                      onClick={onToggleHistoryMode}
                    >
                      退出版本历史
                    </Button>
                  </>
                ) : (
                  <>
                    {activeKey === 'orchestration' && (
                      <div className="flex items-center">
                        {lastAutoSaveTime && !isHistoryMode && (
                          <div className="mr-2 text-[12px] font-normal text-[#474C5F]">
                            已自动保存 {lastAutoSaveTime}
                          </div>
                        )}
                        <div
                          className="cursor-pointer"
                          onClick={onToggleHistoryMode}
                          title="历史版本"
                        >
                          <SvgIcon
                            icon="ic_history"
                            style={{ fontSize: '30px', color: '#E3E3E4' }}
                          />
                        </div>
                      </div>
                    )}
                    {activeKey === 'orchestration' && (
                      <Button
                        className="bg-[#4E5969] text-white"
                        style={buttonStyle}
                        onClick={async () => {
                          try {
                            setSaveStatus(true);
                            await onSave(false);
                          } catch (error) {
                          } finally {
                            setSaveStatus(false);
                          }
                        }}
                        loading={saveStatus}
                      >
                        保存
                      </Button>
                    )}
                    {/* {activeKey === 'orchestration' && (
                    <PublishComponent
                      appId={appId}
                      onSave={onSave}
                      onSwitchToKnowledgeTab={goToKnowledgeTab}
                    />
                  )} */}
                    {userRole == UserRoleEnum.admin && (
                      <PublishComponent
                        // defaultValue={defaultValue}
                        appId={appId}
                        onSave={onSave}
                        onCheck={onCheckTabStatus}
                        onSwitchToKnowledgeTab={goToKnowledgeTab}
                        lastAutoSaveTime={lastAutoSaveTime}
                      />
                    )}
                  </>
                )}
              </div>
            ) : (
              <div className="flex w-[300px] items-center justify-end gap-2"></div>
            )
          ) : (
            <div className="flex w-[150px] items-center gap-2">
              {!previewBtn && (
                <>
                  <Button
                    type="text"
                    onClick={() => {
                      // 如果没有key参数，则跳转工作台
                      // const params = new URLSearchParams(window.location.search);
                      // if (!params.get('key')) {
                      //   router.push(workbench);
                      //   return;
                      // }
                      onApprove && onApprove();
                    }}
                    style={{ color: '#1AA839' }}
                  >
                    通过
                  </Button>
                  <Button
                    type="text"
                    onClick={() => {
                      // 如果没有key参数，则跳转工作台
                      // const params = new URLSearchParams(window.location.search);
                      // if (!params.get('key')) {
                      //   router.push(workbench);
                      //   return;
                      // }
                      onReject && onReject();
                    }}
                    style={{ color: '#FF2604' }}
                  >
                    驳回
                  </Button>
                </>
              )}
            </div>
          )}
        </AntHeader>
      </>
    );
  },
);

export default Header;
